package helper

import (
	"encoding/json"
	"io"
	"mime/multipart"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

func TransferInts(arr []string) (result []int) {
	if len(arr) == 0 {
		return
	}
	for _, v := range arr {
		temp, ok := strconv.Atoi(v)
		if ok != nil {
			continue
		}
		result = append(result, temp)
	}
	return
}

func VerifyJSON(c *gin.Context, obj any) {
	if err := c.ShouldBindBodyWith(obj, binding.JSON); err != nil {
		panic(err.Error())
	}
}

func VerifyJSONArray(c *gin.Context, obj any) {
	body, err := io.ReadAll(c.Request.Body)
	if err != nil {
		panic(err.Error())
	}
	err = json.Unmarshal(body, &obj)
	if err != nil {
		panic(err.Error())
	}
}

func VerifyBody(c *gin.Context, obj any) {
	if err := c.ShouldBind(obj); err != nil {
		panic(err.Error())
	}
}

func VerifyHeader(c *gin.Context, obj any) {
	if err := c.ShouldBindHeader(obj); err != nil {
		panic(err.Error())
	}
}

func VerifyQuery(c *gin.Context, obj any) {
	if err := c.ShouldBindQuery(obj); err != nil {
		panic(err.Error())
	}
}

func VerifyFile(c *gin.Context, name string) (file *multipart.FileHeader) {
	file, err := c.FormFile(name)
	if err != nil {
		panic(err.Error())
	}
	return file
}
